from django.http import HttpResponse
from utils.resFormatUtil import ResFormat
import string, random, os
from PIL import Image, ImageDraw, ImageFont


def verifyParam(*params):
    def verify(func):
        def is_valid(request, *args, **kwargs):
            request_param = getattr(request, request.method)
            for i in params:
                value = request_param.get(i, None)
                if not value:
                    # return HttpResponse('参数错误')
                    return ResFormat(status='PARAM_ERROR').json_response()
            return func(request, *args, **kwargs)

        return is_valid

    return verify


class Imageverify:

    def __init__(self, length=4, width=110, height=40, size=28):
        self.length = length
        self.width = width
        self.height = height
        self.size = size
    # 随机字符
    def random_str(self):
        source = string.ascii_letters + '0123456789'
        return ''.join(random.sample(source, self.length))
    # 随机颜色
    def random_color(self, start, end):
        res = (random.randint(start, end) for i in range(3))
        return tuple(res)
    # 随机线条
    def random_lines(self,draw):
        for i in range(self.length):
            dots = [(random.randint(0,self.width),random.randint(0,self.height)) for i in range(2)]
            draw.line(list(dots),fill=self.random_color(80,255),width=2)
    # 随机点
    def random_dots(self,draw,rate):
        for x in range(self.width):
            for y in range(self.height):
                if random.randint(0,100) <= rate:
                    draw.point((x,y),fill=self.random_color(0,255))

    def image_code(self):
        image = Image.new('RGB', (self.width, self.height), (255, 255, 255))
        # 创建Draw对象
        draw = ImageDraw.Draw(image)
        # 创建Font对象
        file = os.path.dirname(os.path.abspath(__file__))
        font = ImageFont.truetype(f'{file}/HYYakuHei-85W.ttf', self.size)
        # 开始绘画验证码
        code = self.random_str()
        for i in range(self.length):
            draw.text((25 * i + 8, 1), code[i], font=font, fill=self.random_color(80, 200))
        # 绘制干扰线条
        self.random_lines(draw)
        # 绘制干扰点
        self.random_dots(draw,10)
        return image, code

